var page=0;
var lock=0;
var userIds = new Array();
var toUserIds = new Array();
var messageIds = new Array();
var nickName;
var userId;
var regeditPhoneOrName;
var currentPageIndex;// 当前页码数
var currentCount;// 当前总数
var tableData;//存放分页数据
var pattern = new RegExp("[`~！@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？%]");
var chains = /[^\x00-\xff]/ig; //中文符号正则表达式
var update_user = 0;
var datas = {};
var resourceData = {};

layui.use(['jquery','form','layer','laydate','table','laytpl'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;


    //角色列表
    var tableInUser = table.render({
        elem: '#user_list'
        ,toolbar: '#toolbarUsers'
        ,url:request("/console/querySecurityRole")
        ,id: 'user_list'
        ,page: true
        ,curr: 0
        ,limit:Common.limit
        ,limits:Common.limits
        ,groups: 7
        ,cols: [[ //表头
             {field: 'roleName', title: '名称',sort:'true', width:300}
            ,{field: 'roleDesc', title: '描述',sort:'true', width:300}
            ,{field: 'status', title: '状态',sort:'true', width:300,templet(d){
                    if(d.status == 1){
                        return "正常";
                    }else{
                        return "禁用";
                    }
                }}
            ,{fixed: 'right', width: 300,title:"操作", align:'left', toolbar: '#userListBar'}
        ]]
        ,done:function(res, curr, count){
            checkRequst(res);

            //权限判断
            var arr=['role1-add','role1-delete','role1-update','role1-resource'];
            manage.authButton(arr);

          /*  if(count==0&&lock==1){
                layer.msg("暂无数据",{"icon":2});
                renderTable();
            }*/

            var pageIndex = tableInUser.config.page.curr;//获取当前页码
            var resCount = res.count;// 获取table总条数
            currentCount = resCount;
            currentPageIndex = pageIndex;
        }

    });

    //列表操作
    table.on('tool(user_list)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        if (layEvent === 'update'){
            //修改角色
                $.ajax({
                    type:"POST",
                    url:request("/console/querySecirutyRoleById"),
                    data:{id:obj.data.roleId},
                    dataType:'json',
                    async:false,
                    success:function(result){
                        $("#roleIdUpdate").val(result.data.roleId)
                        $("#roleNameUpdate").val(result.data.roleName);
                        $("#roleDescUpdate").val(result.data.roleDesc);
                        $("#roleStatusUpdate").val(result.data.status);
                    }
                })

                $('#title').empty();
                $("#title").append("修改角色");
                $("#roleTable_list").hide();
                $("#add_role").hide();
                $("#update_role").show();
                $("#desc_role").hide();

        }else if (layEvent === 'delete'){
            //删除角色
            layer.confirm('确认要删除吗？', {
                btn : [ '确定', '取消' ]
            }, function(index) {
                $.ajax({
                    type:"POST",
                    url:request("/console/deleteSecurityRole"),
                    data:{
                        id:obj.data.roleId
                    },
                    dataType:'json',
                    async:false,
                    success:function(result){
                        layer.msg("删除成功！", {icon: 1});
                        obj.del();
                    }
                })
            });
        }else if (layEvent === 'lookAuth'){
            //获取该角色所有资源
            $.ajax({
                type:"POST",
                url:request("/console/queryRoleResourceInfo"),
                data:{
                    roleId:obj.data.roleId
                },
                dataType:'json',
                async:false,
                success:function(result){
                    var data =result.data;
                    var html = '<table cellspacing="2" cellpadding="2" border="0" class="layui-table">';
                        html += '<tr><th>资源名称</th><th>资源路径</th><th>资源权限</th></tr>'
                    for(var i=0;i<data.length;i++){
                        html += '<tr><td>' + data[i].resourceName + '</td><td>' + data[i].resourceUrl +'</td><td>' + data[i].resourceAuth +'</td></tr>'
                    }
                     html += ' </table>';

                    layui.layer.open({
                        title: '角色权限'
                        ,type : 1
                        ,offset: 'auto'
                        ,area: ['800px','500px']
                        ,content:  html
                    });

                }
            })
        }else if (layEvent === 'resource'){
            //查看角色权限
            localStorage.setItem("start_page","/pages/console/roleManage.html");
            localStorage.setItem("role_add_resource_roleId",data.roleId);
            window.location.href="/pages/console/roleAddResource.html";
        }else if (layEvent === 'query'){
            //查看该角色下的用户
            var url = "";
            var roleName = obj.data.roleName;
            if (roleName === '机器人'){
                url = "/pages/console/robot.html";
            }else if (roleName === '客服'){
                url = "/pages/console/customer.html";
            }else if (roleName === '财务'){
                url = "/pages/console/finance.html";
            }else if (roleName === '游客'){
                url = "/pages/console/tourist.html";
            }else if (roleName === '普通管理员'){
                url = "/pages/console/admin.html";
            }else if (roleName === '公众号'){
                url = "/pages/console/publicNumber.html";
            }else {
                console.log(data);
                localStorage.setItem("addNewRoleUser_role",obj.data.role);//角色类型
                localStorage.setItem("addNewRoleUser_roleId",obj.data.roleId);//角色编号
                url = "/pages/console/newRoleList.html";
            }

            layer.open({
                type: 2,
                skin: 'layui-layer-rim', //加上边框
                area: ['1000px', '890px'], //宽高
                content: url
            });

        }
    });


    //添加角色表单提交
    $("#role_from_add").click(function () {
        var roleName = $("#roleName").val();
        if (roleName === ""){
            layer.msg('角色名称不能为空！', {icon: 5});
            return;
        }

        var roleDesc = $("#roleDesc").val();
        if (roleDesc === ""){
            layer.msg('角色描述不能为空！', {icon: 5});
            return;
        }

        var roleStatus = $("#roleStatus").val();
        if (roleStatus === ""){
            layer.msg('请选择角色状态！', {icon: 5});
            return;
        }


        $.ajax({
            type:"POST",
            url:request("/console/addSecurityRole"),
            data:{
                roleName:roleName,
                roleDesc:roleDesc,
                status:roleStatus
            },
            dataType:'json',
            async:false,
            success:function(result){
                if(result.resultCode==1){
                    layer.msg("添加成功！",{"icon":1});
                    setTimeout(function(){
                        window.location.href="/pages/console/roleManage.html";
                    }, 1500);
                }else {
                    layer.msg("添加失败，名称有重复！",{"icon":5});
                }
            }
        })
    })

    //修改角色表单提交
    $("#role_from_update").click(function () {
        var roleName = $("#roleNameUpdate").val();
        if (roleName === ""){
            layer.msg('角色名称不能为空！', {icon: 5});
            return;
        }

        var roleDesc = $("#roleDescUpdate").val();
        if (roleDesc === ""){
            layer.msg('角色描述不能为空！', {icon: 5});
            return;
        }

        var roleStatus = $("#roleStatusUpdate").val();
        if (roleStatus === ""){
            layer.msg('请选择角色状态！', {icon: 5});
            return;
        }
        var roleId = $("#roleIdUpdate").val();

        $.ajax({
            type:"POST",
            url:request("/console/addSecurityRole"),
            data:{
                roleId:roleId,
                roleName:roleName,
                roleDesc:roleDesc,
                status:roleStatus
            },
            dataType:'json',
            async:false,
            success:function(result){
                if(result.resultCode==1){
                    layer.msg("修改成功！",{"icon":1});
                    setTimeout(function(){
                        window.location.href="/pages/console/roleManage.html";
                    }, 1500);
                }else {
                    layer.msg("修改失败，名称有重复！",{"icon":5});
                }
            }
        })
    })
});


$(function () {
    $("#roleTable_list").show();
    $("#add_role").hide();
    $("#update_role").hide();
    $("#desc_role").hide();

    //返回按钮
    $(".back").click(function () {
        $('#title').empty();
        $("#title").append("角色列表");
        $("#roleTable_list").show();
        $("#update_role").hide();
        $("#add_role").hide();
        $("#desc_role").hide();
    })

    //获取资源信息
    $.ajax({
        type:"POST",
        url:request("/console/querySelectAllResource"),
        data:{},
        dataType:'json',
        async:false,
        success:function(result){
            resourceData = result.data;
        }
    })
})


var Manage={
    //添加角色
    addRole:function () {
        $('#title').empty();
        $("#title").append("添加角色");
        $("#roleTable_list").hide();
        $("#add_role").show();
        $("#update_role").hide();
        $("#desc_role").hide();
    }
    ,descRole:function () {
        $('#title').empty();
        $("#title").append("角色详情");
        $("#roleTable_list").hide();
        $("#add_role").hide();
        $("#update_role").hide();
        $("#desc_role").show();
    }
}



//重新渲染表单
function renderForm(){
    //use加载所需模块
    layui.use('form', function(){
        var form = layui.form;//高版本建议把括号去掉，有的低版本，需要加()
        form.render();
    });
}


//重新渲染表单
function renderTable(){
    layui.use('table', function(){
        var table = layui.table;//高版本建议把括号去掉，有的低版本，需要加()
        // table.reload("user_list");
        table.reload("user_list",{
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                onlinestate:$("#status").val(),// 在线状态
                keyWord : Common.getValueForElement(".nickName")  //搜索的关键字
            }
        })
    });
}
